# -*- coding: utf-8 -*-
from algo import Algo
from adb import AdbTool
from game import GameStatus, GameBoard
from constant import SWIPE_ERROR
from cvutil import CVTool


class GameController:
    def __init__(self, object_score=4096):
        self.object_score = object_score
        self.game_status = GameStatus()
        self.adb = AdbTool()
        self.algo = Algo()
        self.cv_tool = CVTool(GameBoard.ROW_COUNT, GameBoard.COL_COUNT)
        self.is_connected = False

    def start_game(self):
        if not self.adb.open_adb():
            print('不能连接手机，请检查手机是否连接到电脑！！！')
            self.is_connected = True
        else:
            self.is_connected = True

        return self.is_connected

    def get_status(self):
        return self.game_status

    def next(self):
        self.game_status.inc_step()
        print('-------------------STEP [' + str(self.game_status.get_step()) + ']-------------------')
        self.adb.screen_cap(self.game_status.get_screen_file_name())
        game_board_matrix = self.cv_tool.parse_screen(self.game_status.get_screen_file_name())
        game_board = GameBoard()
        game_board.load_matrix(game_board_matrix)
        if not game_board.is_reg_ok():
            print('OCR failed, retry')
            print('-------------------STEP END-------------------\n')
            return

        print('Current Highest Cell is ' + str(game_board.get_max_cell()))
        empty_cell_count = game_board.total_empty_cells()
        self.algo.adjust_limit(empty_cell_count)
        next_operation = self.algo.determine_next_move(game_board, self.game_status.last_operation)
        if next_operation is not SWIPE_ERROR:
            self.game_status.record_step_operation(next_operation)
            self.adb.set_operation_range(self.cv_tool.ext_rect_x, self.cv_tool.ext_rect_y,
                                         self.cv_tool.ext_rect_w, self.cv_tool.ext_rect_h)
            self.adb.user_swipe(next_operation)
        else:
            self.game_status.record_step_operation(next_operation)
        print('-------------------STEP END-------------------\n')

    def is_game_over(self):
        return self.game_status.is_game_over()

    def show_start_info(self):
        print('目标分数:' + str(self.object_score))

    @staticmethod
    def print_help():
        print('[1]请设置手机')
        print('-锁屏方式设置为[不锁屏]')
        print('-自动灭屏设置为[从不]')
        print('-开发者选项里选择[keep awake]')
        print('[2]请启动游戏，连接手机数据线')

    @staticmethod
    def wait_for_enter_key():
        input('请在手机上开始游戏后，点击任意键')
        print('正式开始游戏......')
